package web

import (
	"net/http"
	"time"
	"io/ioutil"
	"encoding/json"
)


type routerHTTP struct {}

func (*routerHTTP) ServeHTTP(response http.ResponseWriter, request *http.Request) {
	request.ParseForm()

	url := request.URL.Path

	request_type := "200"

	if serverStaticRouter(url, response, request) {
		request_type = "file"
	} else if serverControllerRouter(url, response, request) {
		request_type = "router"
	} else {
		http.Error(response, "404 Not Found", 404)
		request_type = "404"
	}

	webLogger.Info("addr:%s  url:%s type:%s", request.RemoteAddr, url, request_type)

}


//
// 家庭服务中心,Web接入口
// addr: 服务IP地址
// end: 出错关闭程序通道
//
func sevWeb(addr string, end chan bool) {

	setStaticPath("img", staticFilePath + "img")
	setStaticPath("js", staticFilePath + "js")
	setStaticPath("css", staticFilePath + "css")

	SetControllerPath("/login", &LoginController{})
	SetControllerPath("/", &OperateController{})

	ServerHTTP := http.Server{
		Addr: addr,
		Handler: &routerHTTP{},
		ReadTimeout: 5 * time.Second,
	}

	err := ServerHTTP.ListenAndServe()

	if err != nil {
		webLogger.Error("Family Web Server Err: ", err)
	}

	end <- true
}

// 家庭服务地址
type sevWebConf struct {
	SeverAddress		string		`json:"server_address"`
	WebAddress 			string		`json:"family_web_address"`
	WebSocketAddress 	string		`json:"family_web_socket_address"`
}

//
var (
	server_conf_file = "conf/services.json"
)

//
// 开启web服务
// end: app关闭通道
//
func StartService(end chan bool) {
	webLogger.Info("web service: start")

	// 获取配置信息
	// 获取配置信息
	buf, err := ioutil.ReadFile(server_conf_file)
	if err != nil {
		webLogger.Error("services.json not found")
		end <- true
		return
	}

	var conf sevWebConf
	err = json.Unmarshal(buf, &conf)
	if err != nil {
		webLogger.Error("famil server conf err")
		end <- true
		return
	}


	webSocketAddr = "ws://" + conf.SeverAddress + conf.WebSocketAddress

	go sevWeb(conf.WebAddress, end)
	go SevWebSocket(conf.WebSocketAddress, end)

	// 像家庭中心订阅消息
	subscribeFamilyNotify()
}





